﻿// --- Copyright (c) 2010 Steven Hartgers ---
// Copyright (C) 2010 Steven Hartgers All rights are reserved.
// Author contact: fiinix00/at\gmail.com
// ------------------------------------------------------------------------
// This program is free software: you can redistribute it and/or modify 
// it under the terms of the GNU General Public License as published by 
// the Free Software Foundation, either version 3 of the License, or 
// (at your option) any later version. 
//  
// This program is distributed in the hope that it will be useful, 
// but WITHOUT ANY WARRANTY; without even the implied warranty of 
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
// GNU General Public License for more detail
//  
// You should have received a copy of the GNU General Public License 
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
// ------------------------------------------------------------------------
// COPYRIGHT NOTICE: This copyright notice may NOT be removed, obscured or modified 
// without written consent from the author.
// --- End copyright notice --- 


using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Management;
using System.Reflection;
using System.Diagnostics;
using System.Windows.Forms;
using System.ComponentModel;
using System.Collections.Generic;

using Hack;
using Hack.IO;
using Hack.Func;
using Hack.Runtime;
using Hack.Numbers;
using Hack.Security;
using Hack.SystemAPI;
using Hack.Extensions;
using Hack.ScreenCapturing.DirectX.Capture;
using Hack.ScreenCapturing.DirectShowLib;
using System.ComponentModel.Design;
using System.Runtime.InteropServices;
using Hack.Attributes;

using NetFx.AGIL;
using NetFx.SMIL;
using Mono.Cecil;
using Cecil.Decompiler.Cil;
using Cecil.Decompiler.Languages;
using System.Resources;
using ConsoleApplication1.Properties;
using Hack.Numbers.Bytes;
using WMagic = Hack.ThirdParty.Hacking.WhiteMagic.Magic;
using Hack.Converters.Fun;
using Hack.Console;
using Hack.Settings;
using System.Configuration;

using Hack.Security.X509;
using System.Security.Cryptography.X509Certificates;
using Hack.Hacking;
using System.Collections;
using Hack.DllDump;
using System.Web.UI.WebControls;
using System.Web;
using System.Xml.Serialization;
using System.Xml;
using System.Runtime.Serialization;
using Hack.Imageing;
using HMath = Hack.Math;
using SMath = System.Math;

namespace ConsoleApplication1
{
    public static class KnownErrors
    {
        private static List<ErrorK> _KnowsErrors = null;
        public static List<ErrorK> Errors
        {
            get
            {
                if (_KnowsErrors == null)
                    _KnowsErrors = new List<ErrorK>();
                return _KnowsErrors;
            }
        }
        public static void RegisterKnownError(Type type, string VoidName)
        {
            if (_KnowsErrors == null)
                _KnowsErrors = new List<ErrorK>();
            _KnowsErrors.Add(new ErrorK(type, VoidName));
        }

    }
    public class ErrorK
    {
        public Type Type { get; set; }
        public string TypeFullName { get; set; }
        public string VoidName { get; set; }
        public ErrorK(Type type, string voidName)
        {
            this.Type = type;
            this.VoidName = voidName;
            this.TypeFullName = this.Type.FullName;
        }
        /// <summary>
        /// Formats the ErrorK to String
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            return "RegisterKnownError: " + this.TypeFullName + "." + this.VoidName;
        }
    }

    public class SecurePassword : Attribute { }

    public class Program
    {
        internal class EnumWindowList : ArrayList
        {
            private int _EnumComplete = 0;
            private bool _FilterBlanks;
            private bool _FilterHidden;
            private bool _FilterChildren;
            private string[] _FilterStrings;

            public EnumWindowList(bool FilterBlanks, bool FilterHidden, bool FilterChildren, string[] FilterStrings)
            {
                // Creating a new instance of this class returns an ArrayList of Window objects, with one for
                // each window matching the search criteria. I think there must be a better way to create code
                // like this than what I've implemented here -- since EnumWindows is asynchronous, we wait until
                // our callback begins receiving the second round of windows, and then know (or hope) that the
                // callback has been called once for each window.
                _FilterBlanks = FilterBlanks;
                _FilterHidden = FilterHidden;
                _FilterChildren = FilterChildren;
                _FilterStrings = FilterStrings;

                Win32.EnumWindows(new Win32.EnumWindowDelegate(EnumWindowCallBack), 0);
                Win32.EnumWindows(new Win32.EnumWindowDelegate(EnumWindowCallBack), 1);

                while (_EnumComplete == 0)
                    System.Windows.Forms.Application.DoEvents();
            }

            private bool EnumWindowCallBack(IntPtr hwnd, int lParam)
            {
                if (lParam == 0)
                {
                    Window W = new Window(hwnd);
                    bool IsAdd = true;

                    if (_FilterBlanks && W.WindowText == "")
                        IsAdd = false;
                    if (_FilterHidden && !W.IsVisible)
                        IsAdd = false;
                    if (_FilterChildren && W.GetOwner != IntPtr.Zero)
                        IsAdd = false;
                    foreach (string S in _FilterStrings)
                        if (W.WindowText == S)
                            IsAdd = false;

                    if (IsAdd)
                        this.Add(W);
                }

                _EnumComplete = lParam;

                return true;
            }
        }
        public class ColoredConsoleFormater : Cecil.Decompiler.Languages.IFormatter
        {
            #region
            public void Write(string str)
            {
                Console.Write(str);
            }

            public void WriteLine()
            {
                Console.ForegroundColor = NormalColor;
                Console.WriteLine();
            }

            public void WriteSpace()
            {
                Console.ForegroundColor = NormalColor;
                Write(" ");
            }

            public void WriteToken(string token)
            {
                Console.ForegroundColor = TokenColor;
                Write(token);
                Console.ForegroundColor = NormalColor;
            }

            public void WriteComment(string comment)
            {
                Console.ForegroundColor = CommentColor;
                Write(comment);
                Console.ForegroundColor = NormalColor;
            }

            public void WriteKeyword(string keyword)
            {
                Console.ForegroundColor = KeywordColor;
                Write(keyword);
                Console.ForegroundColor = NormalColor;
            }

            public void WriteLiteral(string literal)
            {
                Console.ForegroundColor = LiteralColor;
                Write(literal);
                Console.ForegroundColor = NormalColor;
            }

            public void WriteDefinition(string value, object definition)
            {
                Console.ForegroundColor = DefinitionColor;
                Write(value);
                Console.ForegroundColor = NormalColor;
            }

            public void WriteReference(string value, object reference)
            {
                Console.ForegroundColor = ReferenceColor;
                Write(value);
                Console.ForegroundColor = NormalColor;
            }

            public void WriteIdentifier(string value, object identifier)
            {
                Console.ForegroundColor = IdentifierColor;
                Write(value);
                Console.ForegroundColor = NormalColor;
            }
            public void Indent() { }
            public void Outdent() { }
            #endregion

            private const ConsoleColor NormalColor = ConsoleColor.Gray;
            private const ConsoleColor TokenColor = ConsoleColor.White;
            private const ConsoleColor CommentColor = ConsoleColor.Green;
            private const ConsoleColor KeywordColor = ConsoleColor.Blue;
            private const ConsoleColor LiteralColor = ConsoleColor.Red;
            private const ConsoleColor DefinitionColor = ConsoleColor.Cyan;
            private const ConsoleColor ReferenceColor = ConsoleColor.Yellow;
            private const ConsoleColor IdentifierColor = ConsoleColor.Magenta;
        }
        public static void BrainFuckCompining()
        {
            Mono.Cecil.AssemblyDefinition def = Hack.Compilers.BrainFuck.Compiler.Compile("BrainFuck.Manifest",
@"
            ;; digital root calculator
            ;; written by Keymaker


              >,
              [
                <++++++[>--------<-]>
                [>+<-]>
                [<+>>+<-]
                >[<+>-]<<

                [-[-[-[-[-[-[-[-[-[ [-]
                  >---------<
                ] ] ] ] ] ] ] ] ] ]

                ,
              ]

              ++++++[>++++++++<-]++++++++++>.<."
, true, false, true, true);

            //Mono.Cecil.AssemblyFactory.CreateReflectionAssembly(def).GetTypes().ForEach<Type>((t) =>
            //    {
            //        "New item: ".Out();
            //        t.GetMethods().ForEach<MethodInfo>((mi) =>
            //            {
            //                mi.Name.Out();
            //            });
            //    });
            MemoryStream ms = new MemoryStream();
            //Mono.Cecil.AssemblyFactory.SaveAssembly(def, ms);
            //Assembly asm = Assembly.Load(ms.ToArray());
            Mono.Cecil.AssemblyFactory.SaveAssembly(def, Application.StartupPath + "\\Brain.exe");
            //var method = Cecil.Decompiler.Extensions.Decompile(Cecil.Decompiler.Extensions.


            //asm.GetTypes().ForEach<Type>((t) =>
            //{
            //    if (t.FullName.Contains(".Program"))
            //    {
            //        Type main = asm.GetType(t.FullName, false, false);
            //        //ConstructorInfo ctor = t.GetMethods();//(new Type[] { typeof(object) });//(new Type[] { typeof(string) });

            //        t.GetMethods().ForEach<MethodInfo>((type) =>
            //        {
            //            string _namespace = t.Namespace;
            //            string mainclassName = t.UnderlyingSystemType.Name;
            //            object libraryInstance = null;
            //            if (type.Name.Equals("main", StringComparison.Ordinal))
            //            {
            //                //foreach (Type cls in args.gett)
            //                //{

            //                //    if (type.Name.EndsWith("Class1"))

            //                //        libraryInstance = Activator.CreateInstance(type);

            //                //}
            //                //asm.CreateInstance(_namespace + "." + mainclassName)
            //                ("Found main void\nInvolking static void " + _namespace + "." + mainclassName + ".Main(string[] args)").Out();
            //                MethodInfo method = asm.EntryPoint;
            //                method.Invoke(asm.CreateInstance(method.Name), null);//(asm.CreateInstance(method), null);
            //                //asm.EntryPoint.Invoke(asm.CreateInstance(method), null);
            //                //type.Invoke(null, args);
            //                //MethodInfo entrypoint = t.GetMethod("main");
            //                //_namespace.Out();
            //                //mainclassName.Out();
            //                //run("Program","main",ms.ToArray()).GetType().FullName.Out();
            //                //object instance = new object[]{};//ctor.Invoke(new object[] { "Jon" });
            //                //object instance = Activator.CreateInstance(null, "main");//(null, new object[] { "Hello" });
            //                //instance.GetType().FullName.Out();
            //                //entrypoint.Invoke(entrypoint, null);

            //            }
            //        });
            //        //object instance = ctor.Invoke(new object[] { "Jon" });

            //        //t.GetMethods().ForEach<Type>((type) =>
            //        //    {
            //        //        type.FullName.Out();
            //        //    });
            //    }
            //});




            //Mono.Cecil.AssemblyFactory.CreateReflectionAssembly(def).EntryPoint.Invoke(def.//.Invoke(null, new object[]{}).GetType().FullName.Out();

            //Program p = new Program();
            //p.GetType().Assembly.GetManifestResourceNames().ForEach<string>((str) =>
            //{
            //    str.Out("Resouce: ");
            //});
            //p.GetType().Assembly.GetManifestResourceNames()[0].Out("Reading EXE Resource: ");

            //Stream stream = p.GetType().Assembly.GetManifestResourceStream(p.GetType().Assembly.GetManifestResourceNames()[0]);

            //byte[] asm = new byte[stream.Length];

            //stream.Read(asm, 0, asm.Length);

            //Console.WriteLine(asm.Length);

            //Assembly a = Assembly.Load(asm);

            //MethodInfo mi = a.EntryPoint;

            //mi.Invoke(null, null).GetType().Out("Ran - result: ");





            //string.Format("{0:#-#-#-#}", 1000).Out();
            //FormatMe = 10000000;
            //FormatMe.Format().Out();

        }

        //[Serializable]
        //public class Movie
        //{
        //    [XmlAttribute("MovieName")]
        //    public string Title
        //    { get; set; }
        //    [XmlElement("MovieRating")]
        //    public float Rating
        //    { get; set; }
        //    [XmlElement("MovieReleaseDate")]
        //    public DateTime ReleaseDate
        //    { get; set; }
        //}
        [Serializable]
        public class UserAccount
        {
            [XmlAttribute("Name")]
            public string Name
            { get; set; }

            [XmlAttribute("SecondaryName")]
            public string SecondaryName
            { get; set; }

            [XmlElement("UserCredentials")]
            public UserCredentials Creds
            { get; set; }

            public UserAccount(string name, string secName, UserCredentials cred)
            {
                this.Name = name;
                this.SecondaryName = secName;
                this.Creds = cred;
            }
            public UserAccount()
            {
            }
        }
        [Serializable]
        public class UserCredentials
        {
            [XmlAttribute("Username")]
            public string Username
            { get; set; }

            private string password;
            [XmlAttribute("Password")]
            public string Password
            { get { return this.password; } 
              set { this.password = value.MD5String(); } 
            }

            [XmlAttribute("LostPasswordKey")]
            public string LostPasswordKey
            { get; set; }

            public UserCredentials(string userName, string password, string lostpasskey)
            {
                this.Username = userName;
                this.Password = password;
                this.LostPasswordKey = lostpasskey;
            }
            public UserCredentials()
            {
            }
        }
        public static string SerializeToXML<T>(T movies)
        {
            byte[] bytes = null;
            using (var ms = new MemoryStream())
            {
                XmlSerializer serializer = new XmlSerializer(movies.GetType());
                serializer.Serialize(ms, movies);
                bytes = ms.ToArray();
            }
            return bytes.ToASCII();
        }


        public static void Main(string[] args)
        {
            Hack.Misc.BodyCalculations.Bmi bmi = new Hack.Misc.BodyCalculations.Bmi(Hack.Misc.BodyCalculations.Sex.Man, 16, 185, Hack.Misc.BodyCalculations.Bmi.HeightType.Cm, 58, Hack.Misc.BodyCalculations.Bmi.WeightType.Kg);

            bmi.Out();

            Hack.Misc.BodyCalculations.Bsa.Calculate(185, 58).Out();

            HMath.WeatherDegrees.CelsiusToFahrenheit(20.5).Out();
            //Hack.Authorization.Application application = new Hack.Authorization.Application();
            //application.ApplicationId = new Guid("54875698724658136785461297648254");
            //application.BlockedSince = null;
            //application.CreateDate = new DateTime(2010, 1, 1);
            //application.Description = "Hack Authorization test Application";
            //application.Email = "fiinix00@gmail";
            //application.IsBlocked = false;
            //application.Name = "Hack application No1";
            //application.UnblockedSince = null;

            //Hack.Authorization.Membership membership = new Hack.Authorization.Membership();
            //membership.Description = "Admin";
            //membership.Email = "fiinix00@gmail";
            //membership.LastLoginDate = DateTime.Now;
            //membership.UserId = Guid.NewGuid();
            
            //Hack.Authorization.User user = new Hack.Authorization.User();
            //user.UserName = "StevenH";
            //user.SimultaneousAccess = 1;
            //user.UnblockedSince = null;
            //user.UserId = Guid.NewGuid();
            //user.CreateDate = DateTime.Now;
            //user.Application = application;

            //user.Membership = membership;
            //membership.User = user;

            //Hack.Authorization.Role role = new Hack.Authorization.Role();
            //role.Application = application;
            //role.RoleId = Guid.NewGuid();
            //role.RoleName = "Test Role";

            //Hack.Forms.PasswordDialog dialog = new Hack.Forms.PasswordDialog();
            //Application.Run(dialog);


            //Tests.Tests.RssReadingTest();
            //Tests.Tests.SchedulerTest();


            //Tests.TestRuner.RunAllTests(false);
            
          

            #region SerializeTestCode
		            //List<UserAccount> movies = new List<UserAccount>();
            //movies.Add(new UserAccount("Steven", "Hartgers", new UserCredentials("fiinix00", "Hello", "184481561")));
            //movies.Add(new UserAccount("Patrik", "Tjernström", new UserCredentials("Patrik", "ItGymnasiet", "685454818")));


            //SerializeToXML(movies).Out();

            //Hack.Validation.PhoneValidator.IsValidNumber("220", "Sweden").Out();


            //Hack.Image.AsciiArtImage.ConvertToAscii(Hack.Image.AsciiArtImage.GetReSizedImage(Tests.Tests.TestBitmap, 10)).Out();





            //List<Movie> movies = new List<Movie>();
            //movies.Add(new Movie()
            //               {
            //                   Rating = 10.0f,
            //                   ReleaseDate = new DateTime(2010, 05, 12),
            //                   Title = "Lolz movie - The Returning"
            //               });
            //movies.Add(new Movie()
            //               {
            //                   Title = "Starship Troopers",
            //                   ReleaseDate = DateTime.Parse("11/7/1997"),
            //                   Rating = 6.9f
            //               });


            //SerializeToXML(movies).Out();

            /*
                      public static byte[] Serialize(this Object o)
        {
            var ms = new MemoryStream();
            var bf = new BinaryFormatter();
            bf.Serialize(ms, o);
            return ms.ToArray();
        }
        public static object DeSerialize(this byte[] b)
        {
            var ms = new MemoryStream(b);
            var formatter = new BinaryFormatter();
            return formatter.Deserialize(ms);
        }   
	
                */
#endregion
            //serme.Serialize().Out();
#if DEBUG
            KnownErrors.RegisterKnownError(typeof(Hack.Pdb2Mdb.Converter), "ConvertFunction");
            KnownErrors.RegisterKnownError(typeof(System.Console), "WriteLine");
            
            //KnownErrors.RegisterKnownError(typeof(Hack.Data.Linq.CompiledQuery), "Func");
            //KnownErrors.RegisterKnownError(typeof(Hack.Data.Linq.Expressions), "MapMember");
            //KnownErrors.RegisterKnownError(typeof(Hack.Data.Linq.Extensions), "LambdaExpression");
            //KnownErrors.Errors
            //    .ForEach((error) =>
            //                 {
            //                     error.Out();
            //                 });
#endif
            #region OldCode
            //http://code.google.com/p/csharptest-net/source/browse/trunk/src/SslTunnel#SslTunnel/Library
            //Cecil.Decompiler.Languages.CSharp c = new CSharp();
            //MethodInfo m = typeof(object).GetMethod("ToString");
            //MethodBody mb = m.GetMethodBody();
            //byte[] ilb = mb.GetILAsByteArray();
            //for (int i = 0; i < ilb.Length; i++)
            //    Console.Write("{0:X} ", ilb[i]);

            //MethodBase.GetMethodFromHandle((((Action<Type,string>)RegisterKnownError).Method.MethodHandle));
            //Tests.RunAllTests();
            //Tests.CommandInterpreterTest(args);


            //((Action)BrainFuckCompining).Inspect();
            //((Action)BrainFuckCompining).InspectILBytes();



            //byte[] Ils = MethodBase.GetMethodFromHandle(((Action)BrainFuckCompining).Method.MethodHandle)
            //    .GetMethodBody()
            //        .GetILAsByteArray();
            //int len = 0;

            //string code = Hack.DllDump.Disassembler.Decode(Ils, 0, out len);
            //for (int i = 0; i < len; i++)
            //{
            //    Console.WriteLine(Hack.DllDump.Disassembler.Decode(Ils, i, out len));
            //}




            //Action<string, Table> WriteLineToTable = (line, tblCode) => 
            //{
            //    TableRow tr = new TableRow();
            //    TableCell td = new TableCell();
            //    td.HorizontalAlign = HorizontalAlign.Left;
            //    tr.Cells.Add(td);
            //    string from;
            //    from = HttpUtility.HtmlEncode(line);
            //    /*
            //     * Replace all spaces with &nsbp;
            //     */
            //    from = from.Replace(" ", "&nbsp;");
            //    /*
            //    * Replace all tabs with 6 * &nsbp;
            //    */
            //    from = from.Replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
            //    /*
            //     * If this line is blank put in one space (blank lines are supposed to be visible)
            //     */
            //    if (from.Trim() == "") from = "&nbsp;";

            //    td.Text = from;

            //    tblCode.Rows.Add(tr);
            //};


            //Assembly assembly = System.Reflection.Assembly.GetAssembly(typeof(DLL));
            //if (assembly == null) throw new Exception("Error loading DLL");

            //DLL thedll = new DLL(assembly);
            //thedll.ShowCode = true;
            //StringWriter sw = new StringWriter();
            //thedll.ToString(sw);

            //string result = sw.ToString();

            //StringReader rdr = new StringReader(result);

            //while (true)
            //{
            //    string record = rdr.ReadLine();
            //    if (record == null) break;
            //    //WriteLineToTable(record, tblCode);
            //    Console.WriteLine(record);
            //}

            //rdr.Close();





            //            var line = File.ReadAllText(@"C:\Users\Steven\Documents\My Dropbox\Mina filer\Hack\Hack\Extensions\Extensions.cs");

            //            var lines = line.Split(new string[] { "[Extension]" }, StringSplitOptions.None);
            //            var _li = lines.ToList();
            //            _li.RemoveAt(0);
            //            int i = 0;
            //            string pattern = "\r\n    public static class";
            //            _li.ForEach((_line) => 
            //            {
            //                int index = _line.IndexOf(pattern) + pattern.Length;
            //                string newFileName = @"C:\Users\Steven\Documents\My Dropbox\Mina filer\Hack\Hack\Extensions\_ext"+i.ToString<int>()+".cs";

            //                string fileStruct = @"namespace Hack.Extensions._ext" + i++.ToString<int>() + @"
            //{
            //[Extension]
            //" + _line+@"
            //}";
            //                File.Create(newFileName).Close();
            //                File.WriteAllText(newFileName, fileStruct);
            //            });




            //MethodDefinition methos = new MethodDefinition("Main", Mono.Cecil.MethodAttributes.Public | Mono.Cecil.MethodAttributes.Static, null);
            //ControlFlowGraph cfg = ControlFlowGraph.Create(methos);

            //var lang = CSharp.GetLanguage(CSharpVersion.V3);
            //var writer = lang.GetWriter(new ColoredConsoleFormater());
            //writer.Write(methos);
            //TheNeverHoodBLB blb = new TheNeverHoodBLB();
            //blb.Begin();
            //BarcodeLib.Symbologies.Code39 code = new BarcodeLib.Symbologies.Code39("SOD09024", true);

            //Hack.Security.X509.X509CertificateBuilder
            //System.Security.Cryptography.X509Certificates.X509Store store = new System.Security.Cryptography.X509Certificates.X509Store("My", StoreLocation.CurrentUser);
            //store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
            ////foreach (X509Certificate2 tempCert in store.Certificates)
            ////{

            ////}
            //store.Certificates.ForEach<X509Certificate2>((cer,i) => 
            //{
            //    Console.WriteLine(cer.SerialNumber);
            //});


            //Hack.Extensions.ClassExtensions.Inspect<bool>(

            //Random random = new Random();

            //float[] iArr = new float[99999999];
            //iArr.Initialize();
            //(1000000).Times(() => 
            //{
            //    //iArr[Hack.Extensions.Extensions.GaussianRandom(random).X1] + 1.0;
            //    //iArr[]++;//random.Next(0, 1000000)]++;
            //});

            //float biggestIndex = 0;
            //int ZeroIndexes = 0;
            //iArr.ForEach((item) => 
            //{
            //    if (item > biggestIndex)
            //        biggestIndex = item;
            //    if (item < 1)
            //        ZeroIndexes++;
            //});
            //biggestIndex.Out("Winner: ");
            //ZeroIndexes.Out("Empty indexes: ");
            //);

    
            //
            //var r = Hack.Pdb2Mdb.PdbFile.LoadFunctions(File.OpenRead(""), false);//(Stream)File.Open("pdb", FileMode.Open), true);
            #region Hook Test - NonWorking
            //Form f = new Form();

            //List<Window> ListWindows = new List<Window>();
            //ArrayList _Windows = null;
            //GlobalHooks hook = new GlobalHooks(f.Handle);
            //bool _IsRunning = false;

            //Action UpdateWindowList = () =>
            //{
            //    ListWindows.Clear();
            //    if (_Windows != null)
            //        foreach (Window W in _Windows)
            //            ListWindows.Add(W);
            //};

            //Action Start = () =>
            //{
            //    if (!_IsRunning)
            //    {
            //        _IsRunning = true;

            //        // Return a list of all open, titled, top-level windows (excluding the "Program Manager" window, which Microsoft has kept as a top-level window since Windows 3.0, just to be a real pain in the butt to us programmers
            //        _Windows = new EnumWindowList(true, true, true, new string[] { "Program Manager" });

            //        // Start hooking
            //        hook.Shell.Start();
            //        hook.GetMsg.Start();
            //    }
            //};
            //Action Stop = () =>
            //{
            //    if (_IsRunning)
            //    {
            //        // Remove our hooks
            //        hook.Shell.Stop();
            //        hook.GetMsg.Stop();

            //        // Iterate through all windows we've been monitoring, undoing any changes we've done to them
            //        if (_Windows != null)
            //            foreach (Window W in _Windows)
            //                W.StopManaging();

            //        _Windows = null;
            //        _IsRunning = false;
            //    }

            //};
            //Func<IntPtr, Window> FindWindow = (Handle) =>
            //{
            //    foreach (Window W in _Windows)
            //        if (W.Handle == Handle)
            //            return W;

            //    return null;
            //};





            //hook.Shell.WindowCreated += (Handle) =>
            //{
            //    // This event is called when a new top-level window is created. We create a Window object to function
            //    // as an internal wrapper to this window.
            //    Window W = new Window(Handle);
            //    _Windows.Add(W);

            //    UpdateWindowList();
            //};
            //hook.Shell.WindowDestroyed += (Handle) =>
            //{
            //    // This event is called when a top-level window is destroyed. Since the window is being destroyed,
            //    // it's not really necessary to undo all the changes we've made to it, but hey, it can't hurt either.
            //    int w = -1;

            //    for (int i = 0; i < _Windows.Count; ++i)
            //        if (((Window)_Windows[i]).Handle == Handle)
            //        {
            //            w = i;
            //            break;
            //        }

            //    if (w != -1)
            //    {
            //        ((Window)_Windows[w]).StopManaging();
            //        _Windows.RemoveAt(w);
            //    }

            //    UpdateWindowList();
            //};
            //hook.GetMsg.GetMsg += (Handle, Message, wParam, lParam) =>
            //{
            //    if (Message.ToInt32() == Win32.WM_SYSCOMMAND)
            //    {
            //        int LowOrder = (wParam.ToInt32() & 0x0000FFFF);
            //        int HighOrder = wParam.ToInt32() - LowOrder;

            //        Window W = FindWindow(Handle);
            //        if (W != null)
            //        {
            //            if (LowOrder == Win32.SC_FADEOUT)
            //                W.FadeOut();
            //            else if (LowOrder == Win32.SC_FADEIN)
            //                W.FadeIn();
            //            else if (LowOrder == Win32.SC_TRANS100)
            //                W.SetTransparency(255);
            //            else if (LowOrder == Win32.SC_TRANS95)
            //                W.SetTransparency(242);
            //            else if (LowOrder == Win32.SC_TRANS90)
            //                W.SetTransparency(230);
            //            else if (LowOrder == Win32.SC_TRANS85)
            //                W.SetTransparency(217);
            //            else if (LowOrder == Win32.SC_TRANS80)
            //                W.SetTransparency(204);
            //            else if (LowOrder == Win32.SC_TRANS75)
            //                W.SetTransparency(191);
            //            else if (LowOrder == Win32.SC_TRANS70)
            //                W.SetTransparency(179);
            //            else if (LowOrder == Win32.SC_TRANSCLEAR)
            //                W.ClearTransparency();
            //        }
            //    }
            //};
            //Start();
            //UpdateWindowList();


            //Stop();
            //UpdateWindowList();
            #endregion


            //Hack.Hacking.GlobalHooks.MouseHook mh = new Hack.Hacking.GlobalHooks.MouseHook(
            //((Action)b.CreateControl).Inspect();


            //Hello(10);
            //Hack.Extensions.Extensions.FastForm((form) =>
            //{
            //    form.BackgroundImageLayout = ImageLayout.Stretch;
            //    //form.BackgroundImage = Tests.TestBitmap.Add(ImageExtensions.ManipulationColors.Blue, 5f);
            //    Bitmap n = new Bitmap(60, 60);
            //    Graphics g = Graphics.FromImage(n);

            //    Icon MyIcon = Icons.GetFileIcon(@"C:\Program Files (x86)\Adobe\Reader 9.0\Reader\AcroRd32.exe", Icons.SHGFISize.SHGFI_LARGEICON);
            //    g.DrawIcon(MyIcon, 10,10);
            //    MyIcon.Dispose();

            //    g.Dispose();
            //    form.BackgroundImage = n;

            //}, new Control[]
            //{

            //});


            #region problem ... http://csharptest.net/?p=300
            //Configuration cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
            //UserSettingsSection settings = UserSettingsSection.UserSettingsFrom(cfg);
            ////problem ... http://csharptest.net/?p=300
            //settings["a"] = "b";
            //var r = settings.Sections["c"] = new UserSettingsSubSection();
            //settings.Sections["c"]["x"] = "y";
            ////save the configuration
            //cfg.Save();
            #endregion



            //Message._1337(_1337Speek._1337LanguageStyle.Warez_d00dz__English, _1337Speek._1337CaseStyle.ALL_UPPER_CASE, _1337Speek._1337LameStyle.None, false).Out();
            //int hmod = Hack.SystemAPI.NativeDlls.LoadLibrary("User32");
            //int funcaddr = Hack.SystemAPI.NativeDlls.GetProcAddress(hmod, "MessageBoxW");
            //int result = Hack.SystemAPI.NativeDlls.InvokeFunc(funcaddr, 0, "Hello World",
            //                      ".Net dynamic export invocation", 1 /*MB_OKCANCEL*/);
            //Console.WriteLine("Result of invocation is " + result);

            //Hack.SystemAPI.NativeDlls.FreeLibrary(hmod);
            #endregion
            
            Console.Read();

        }




        static object run(string classname, string methodname, byte[] asmBytes)
        {
            Assembly asm = Assembly.Load(asmBytes);
            Type type = asm.GetType(classname);
            object obj = asm.CreateInstance(classname);
            object[] args = new object[0];
            object ret = type.InvokeMember(
              methodname,
              BindingFlags.Default | BindingFlags.InvokeMethod,
              null,
              obj,
              args
            );
            return ret;
        }

        public static Hack.ActionDisposable SetupConsole()
        {
            var originalBackgroundColor = Console.BackgroundColor;
            var originalForegroundColor = Console.ForegroundColor;
            return new ActionDisposable(() =>
            {
                Console.BackgroundColor = originalBackgroundColor;
                Console.ForegroundColor = originalForegroundColor;
            });

        }
        public static ActionDisposable SetupConsole(Action preInit)
        {
            return new ActionDisposable(() => { preInit(); SetupConsole(); });
        }
    }


    //internal static class TestsFjortisDir
    //{
    //    public class FjortisList<T> : IEnumerable<T> where T : struct
    //    {
    //        public IEnumerator<T> GetEnumerator()
    //        {
    //            return items.GetEnumerator();
    //        }
    //        public List<T> items { get; internal set; }
    //        public void Add(T item)
    //        {
    //            items.Add(item);
    //        }
    //        public FjortisList()
    //        {
    //            items = new List<T>();
    //        }
    //    }
    //    public class FjortisDir : FjortisList<Object>
    //    {
    //        public IEnumerator<Object> GetEnumerator()
    //        {
    //            return base.GetEnumerator();
    //        }

    //        public String MapName { get; set; }
    //        //public List<String> Filer { get; set; }
    //        //public string[] Filer { get; set; }
    //        public FjortisDir(String MapName)
    //        {
    //            this.MapName = MapName;
    //        }
    //        public FjortisDir(String MapName, string[] filer)
    //        {
    //            //Filer = filer.ToList();
    //            base.Add(filer);
    //            this.MapName = MapName;
    //        }
    //        public FjortisDir(String MapName, List<String> filer)
    //        {
    //            base.Add(filer);
    //            this.MapName = MapName;
    //            //Filer = filer;
    //        }
    //        public FjortisDir()
    //        {
    //        }
    //        public FjortisDir(String MapName, List<String> filer, FjortisDir nerDir)
    //        {
    //            base.Add(filer);
    //            base.Add(nerDir);
    //            NerDir = nerDir;
    //            this.MapName = MapName;
    //            //this.Filer = filer;

    //        }
    //        public FjortisDir NerDir = null;
    //    }
    //    public static void Test()
    //    {
    //        List<FjortisDir> Fjortis_se = new List<FjortisDir>();

    //        Fjortis_se.Add(new FjortisDir
    //        {
    //            new FjortisDir("home") { new FjortisDir("viktor") { new FjortisDir("domains") {
    //                        new FjortisDir("fjortis.se")
    //                        {
    //                            new FjortisDir("public_html") //Main Dir http://www.fjortis.se/
    //                            {
    //                                "index.php",
    //                                 new FjortisDir("file")
    //                                {
    //                                     new FjortisDir("style")
    //                                    {
    //                                        new FjortisDir("lilac")
    //                                        {
    //                                            "style.php?v=1620"
    //                                        }
    //                                    },
    //                                    new FjortisDir("cache")
    //                                    {

    //                                    }
    //                                },                
    //                                new FjortisDir("design")
    //                                {
    //                                    "favicon.png",
    //                                    new FjortisDir("static")
    //                                    {
    //                                       "index.php?f=32CHARLEN&t=CSSJS"
    //                                    }
    //                                },
    //                                new FjortisDir("plugins")
    //                                {
    //                                    new FjortisDir("wysiwyg")
    //                                    {
    //                                        "style.css"
    //                                    }
    //                                }
    //                            }
    //                        }
    //           } } } });
    //    }
    //}
}